/*
	Lists a count of all of the SBG records in all databases.
	
	Easily modifyable to perform mass acctions on all databases on a server, etc.
*/

DECLARE @db_name VARCHAR(255)
DECLARE @chk_db VARCHAR(255)
DECLARE @rcd_cnt INTEGER
DECLARE @sql_script VARCHAR(8000)

CREATE TABLE #tmp_sbg
(
	db VARCHAR(255),
	rcd_cnt INTEGER
)

DECLARE db_cursor CURSOR FOR
SELECT 
	[name] 
FROM master..sysdatabases
WHERE LEFT([name], 3) = 'DST'

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @db_name

SET @sql_script = 'INSERT INTO #tmp_sbg (db, rcd_cnt) ('

WHILE @@FETCH_STATUS = 0
BEGIN
	SET @sql_script = @sql_script + ' (SELECT ''' + @db_name + ''', COUNT(*) FROM [' + @db_name + ']..[SBG]) UNION'
	FETCH NEXT FROM db_cursor INTO @db_name
END

CLOSE db_cursor
DEALLOCATE db_cursor

SET @sql_script = LEFT(@sql_script, LEN(@sql_script) - 6) + ')'

print @sql_script
EXECUTE (@sql_script)

SELECT * 
FROM #tmp_sbg
GO

DROP TABLE #tmp_sbg
GO